package com.yungam.imcs.controller.person;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yungam.common.bean.team.Team;
import com.yungam.common.bean.user.User;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.TeamService;
import com.yungam.common.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "班组管理页面接口")
@RestController
@RequestMapping("/teams")
public class TeamController {

    @Resource
    private TeamService teamService;
    @Resource
    private UserService userService;

    @ApiOperation("获取所有的班组信息")
    @GetMapping("/team")
    public RetDTO<?> getTeams() {
        QueryWrapper<Team> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        List<Team> teams = teamService.list(qw); // 班组
        // 存放 <team_id, leader_id> 键值对
        Map<Integer, Integer> leaderMapper = new HashMap<>();
        for (Team team : teams) leaderMapper.put(team.getId(), team.getLeaderId());
        List<User> users = userService.list();
        Map<Integer, List<User>> map = new HashMap<>(); // 存放 <team_id, User> 的键值对
        for (User user : users) {
            if (Objects.isNull(user.getTeamId())) continue; // 没有小组则跳过
            List<User> list = map.getOrDefault(user.getTeamId(), new ArrayList<>());
            // 组长添加在第一位
            if (Objects.equals(user.getId(), leaderMapper.get(user.getTeamId()))) list.add(0, user);
            else list.add(user);
            map.put(user.getTeamId(), list);
        }
        // 组装『班组成员』属性
        for (Team team : teams) {
            team.setTeamMembers(map.getOrDefault(team.getId(), new ArrayList<>()));
        }
        Map<String, Object> ans = new HashMap<>();
        ans.put("tableData", teams);
        ans.put("selectOptions", users);
        return RetDTO.data(ans);
    }

    @ApiOperation("添加班组")
    @PostMapping("/team")
    public RetDTO<?> addTeam(@ApiParam("班组实体") @RequestBody Team team) {
        List<Integer> memberIds = team.getMemberIds();
        // 查重
        QueryWrapper<Team> qw = new QueryWrapper<>();
        qw.eq("team_no", team.getTeamNo()).or().eq("team_name", team.getTeamName());
        if (teamService.getOne(qw) != null) return RetDTO.error("该班组编号或者名称已存在");
        team.setCreateTime(new Date());
        teamService.save(team); // 保存班组
        // 更新班组成员信息
        QueryWrapper<Team> qw1 = new QueryWrapper<>();
        // 获取刚刚插入的班组id
        if (!memberIds.contains(team.getLeaderId())) memberIds.add(team.getLeaderId()); // leaderId 也需要更新
        qw1.eq("team_no", team.getTeamNo());
        Team cur = teamService.getOne(qw);
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.in("id", memberIds).set("team_id", cur.getId());
        userService.update(uw);
        return RetDTO.success();
    }

    @ApiOperation("删除班组")
    @DeleteMapping("/team")
    public RetDTO<?> delTeam(@ApiParam("班组 id") Integer id) {
        teamService.removeById(id);
        // 清空组员信息
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.eq("team_id", id).set("team_id", null);
        userService.update(uw);
        return RetDTO.success();
    }

    @ApiOperation("修改班组")
    @PutMapping("/team")
    public RetDTO<?> updateTeam(@ApiParam("班组实体") @RequestBody Team team) {
        List<Integer> memberIds = team.getMemberIds();
        // 如果班组编号或者名称发生改变, 则需要查重
        Team old = teamService.getById(team.getId());
        if (!Objects.equals(team.getTeamNo(), old.getTeamNo())) {
            QueryWrapper<Team> repeat = new QueryWrapper<>();
            repeat.eq("team_no", team.getTeamNo());
            if (teamService.getOne(repeat) != null) return RetDTO.error("该班组编号已存在");
        }
        if (!Objects.equals(team.getTeamName(), old.getTeamName())) {
            QueryWrapper<Team> repeat = new QueryWrapper<>();
            repeat.eq("team_name", team.getTeamName());
            if (teamService.getOne(repeat) != null) return RetDTO.error("该班组名称已存在");
        }
        teamService.updateById(team); // 保存班组
        // 更新班组成员信息, 与原来的成员信息比对, 如果现在不在该组, 则清空 team_id 字段, 新加入成员则添加 team_id
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.eq("team_id", team.getId());
        List<Integer> oldList = userService.list(userQw).stream().map(v -> v.getId()) // 旧信息
                                           .collect(Collectors.toList());
        List<Integer> toAdd = new ArrayList<>(), toDel = new ArrayList<>();
        for (Integer num : memberIds) if (!oldList.contains(num)) toAdd.add(num);
        for (Integer num : oldList) if (!memberIds.contains(num)) toDel.add(num);
        // 判断班组组长是否更换
        if (!old.getLeaderId().equals(team.getLeaderId()) && !toAdd.contains(team.getLeaderId())) toAdd.add(team.getLeaderId());
        UpdateWrapper<User> uwAdd = new UpdateWrapper<>(), uwDel = new UpdateWrapper<>();
        if (toAdd.size() > 0) {
            uwAdd.in("id", toAdd).set("team_id", team.getId());
            userService.update(uwAdd);
        }
        if (toDel.size() > 0) {
            uwDel.in("id", toDel).set("team_id", null);
            userService.update(uwDel);
        }
        return RetDTO.success();
    }

}
